package Frontera;

import DAO.ProductosProveedorJpaController;
import Entidad.ProductoProveedor;
import java.util.List;
import java.util.Vector;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;

public class ProductoProveedorInterfaz extends javax.swing.JFrame {

    EntityManager em;
    
    public ProductoProveedorInterfaz(Vector lista){
        em = Splash.em;
        initComponents();
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        modelo = new MiModelo();
        tabla = new JTable(modelo);
        Vector titulos = new Vector();
        titulos.add("Producto");
        titulos.add("Precio");
        modelo.setDataVector(lista, titulos);
        jScrollPane1.setViewportView(tabla);
    }

    public ProductoProveedorInterfaz(ProductosProveedorJpaController listaProductos) {
        em = Splash.em;
        initComponents();
        listaLocal = listaProductos.getProductosProveedor(em);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        modelo = new MiModelo();
        tabla = new JTable(modelo);
        modelo.addColumn("Producto");
        modelo.addColumn("Precio");

        for(ProductoProveedor u: listaProductos.getProductosProveedor(em)){
            Vector obj = new Vector();
            obj.add(u.getNombreProducto());
            obj.add(u.getPrecioPorUnidad());
            modelo.addRow(obj);
        }
        jScrollPane1.setViewportView(tabla);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        BtnAñadir = new javax.swing.JButton();
        BtnBorrar = new javax.swing.JButton();
        BtnCancelar = new javax.swing.JButton();
        BtnGuardar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        BtnAñadir.setText("Añadir");
        BtnAñadir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnAñadirActionPerformed(evt);
            }
        });

        BtnBorrar.setText("Borrar Fila");
        BtnBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnBorrarActionPerformed(evt);
            }
        });

        BtnCancelar.setText("Cancelar");
        BtnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnCancelarActionPerformed(evt);
            }
        });

        BtnGuardar.setText("Guardar Cambios");
        BtnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnGuardarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 285, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(BtnCancelar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
                    .addComponent(BtnBorrar, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
                    .addComponent(BtnAñadir, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
                    .addComponent(BtnGuardar, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(BtnAñadir)
                .addGap(18, 18, 18)
                .addComponent(BtnBorrar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE)
                .addComponent(BtnGuardar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(BtnCancelar)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BtnAñadirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnAñadirActionPerformed
        Vector obj= new Vector();
        this.setVisible(false);
        String producto = JOptionPane.showInputDialog("Producto");
        String precio = JOptionPane.showInputDialog("Precio");
        if(producto != null){
            if(precio != null){
                Float valor;
                try{
                    valor = Float.parseFloat(precio);
                }catch(NumberFormatException ex){
                    valor = new Float(-1);
                }
                if(valor >= 0){
                    producto = estandarizarNombre(producto);
                    if(validarNombre(producto)){
                        obj.add(producto);
                        obj.add(valor);
                        modelo.addRow(obj);
                    }else{
                        JOptionPane.showMessageDialog(null, "El nombre ya existe");
                    }
                }else{
                    JOptionPane.showMessageDialog(null, "Precio no valido");
                }
            }else{
                JOptionPane.showMessageDialog(null, "Precio no valido");
            }
        }else{
            JOptionPane.showMessageDialog(null, "Nombre no valido");
        }
        this.setVisible(true);
    }//GEN-LAST:event_BtnAñadirActionPerformed

    private void BtnBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnBorrarActionPerformed
        System.out.println(modelo.getDataVector().isEmpty());
        if(!modelo.getDataVector().isEmpty()){
            int size=0;

            int filaBorrar = 0;
            try{
                size = modelo.getDataVector().size();
            }catch(NullPointerException ex){
                size = 0;
            }
            filaBorrar = tabla.getSelectionModel().getLeadSelectionIndex();
            if(filaBorrar == -1 && size > 0){
                filaBorrar = size - 1;
            }
            if(filaBorrar >= size){
                modelo.removeRow(filaBorrar);
            }
            else if( JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(frame, "Esta seguro que desea\n eliminar este producto?", "Confirmacion" ,JOptionPane.YES_NO_OPTION)){
                modelo.removeRow(filaBorrar);
            }
        }else{
            JOptionPane.showMessageDialog(null, "No se puede borrar");
        }
    }//GEN-LAST:event_BtnBorrarActionPerformed

    private void BtnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnCancelarActionPerformed
        Splash.listaproductos = null;
        this.dispose();
    }//GEN-LAST:event_BtnCancelarActionPerformed

    private void BtnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnGuardarActionPerformed
        Vector lista = new Vector();
        lista = modelo.getDataVector();
        Splash.listaproductos = lista;
        this.dispose();
    }//GEN-LAST:event_BtnGuardarActionPerformed

    private boolean validarNombre(String nombre){
        Vector nombres = modelo.getDataVector();
        for (int i=0; i< nombres.size(); i=i+2){
            if(((Vector)nombres.elementAt(i)).get(0).equals(nombre)){
                return false;
            }
        }
        return true;
    }

    private String estandarizarNombre(String nombre){
        String nuevo="";
        nuevo = nuevo + Character.toUpperCase(nombre.charAt(0));
        for (int i=1; i < nombre.length(); i++){
            if(nombre.charAt(i)>= 'A' && nombre.charAt(i) <= 'Z' ){
                nuevo = nuevo + Character.toLowerCase(nombre.charAt(i));
            }else{
                nuevo = nuevo + nombre.charAt(i);
            }
        }
        return nuevo;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BtnAñadir;
    private javax.swing.JButton BtnBorrar;
    private javax.swing.JButton BtnCancelar;
    private javax.swing.JButton BtnGuardar;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
    private JTable tabla;
    private MiModelo modelo;
    private List<ProductoProveedor> listaLocal;
    private JFrame frame;
}
